package main

import (
	"context"
	"fmt"
	"github.com/grpc-ecosystem/go-grpc-middleware/retry"
	"google.golang.org/grpc"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/credentials/insecure"
	"oldpackagetest/grpc_interprotor/proto"
	"time"
)

func main() {
	//拦截器：计算耗时时间
	interceptor := func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
		start := time.Now()
		err := invoker(ctx, method, req, reply, cc, opts...)
		fmt.Printf("耗时：%s\n", time.Since(start))
		return err
	}
	//opt := grpc.WithUnaryInterceptor(interceptor)
	//定义多个拦截器
	var opts []grpc.DialOption
	opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	//grpc_retry实现超时重试
	retryOpts := []grpc_retry.CallOption{
		grpc_retry.WithMax(3),                                                          //重试最多3次
		grpc_retry.WithPerRetryTimeout(1 * time.Second),                                //每次最高超时1秒
		grpc_retry.WithCodes(codes.Unknown, codes.DeadlineExceeded, codes.Unavailable), //基于返回codes判断超时机制
	}
	//添加拦截器
	opts = append(opts, grpc.WithUnaryInterceptor(interceptor))
	opts = append(opts, grpc.WithUnaryInterceptor(grpc_retry.UnaryClientInterceptor(retryOpts...)))
	//建立连接
	conn, err := grpc.Dial("127.0.0.1:8081", opts...)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	c := proto.NewGreeterClient(conn)
	//调用
	r, err := c.SayHello(context.Background(), &proto.HelloRequest{Name: "jzin"})
	if err != nil {
		panic(err)
	}
	fmt.Println(r.Message)
}
